var createError = require('http-errors');
var express = require('express');
var path = require('path');
// 处理cookie
var cookieParser = require('cookie-parser');
// 打印日志
var logger = require('morgan');

//引入路由中间件（自定义路由中间件）
var indexRouter = require('./routes/index');
var goodsRouter = require('./routes/goods');
var bannerRouter = require('./routes/banner');
var usersRouter = require('./routes/users');
var orderRouter = require('./routes/order');
var messageRouter = require('./routes/message');

// 创建服务对象
var app = express();

// view engine setup
// 找到页面模板的文件路径，设置给服务对象
app.set('views', path.join(__dirname, 'views'));

// 设置页面模板的渲染引擎是ejs
app.set('view engine', 'ejs');

// 注册工具类中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 注册路由中间件
app.use('/', indexRouter);
app.use('/index', indexRouter);
app.use('/goods', goodsRouter);
app.use('/banner', bannerRouter);
app.use('/users', usersRouter);
app.use('/order', orderRouter);
app.use('/message', messageRouter);

// catch 404 and forward to error handler
// 注册404报错提示
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    // 注册服务器报错
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;